from django.db import models

class Clazz(models.Model):
    cno = models.AutoField(primary_key=True)
    cname = models.CharField(max_length=100)
    def __str__(self):
        return u'Clazz:%s'%self.cname

# 课程
class Course(models.Model):
    course_no = models.AutoField(primary_key=True)
    course_name = models.CharField(max_length=100)
    def __str__(self):
        return u'Course:%s'%self.course_name

# 学生表（多）
class Student(models.Model):
    sno = models.AutoField(primary_key=True)
    sname = models.CharField(max_length=100)
    cla = models.ForeignKey(Clazz,on_delete=models.CASCADE)
    cour = models.ManyToManyField(Course)

    def __str__(self):
        return u'Student:%s'%self.sname

#根据班级名称,获取班级对象
def getCls(cname):
    try:
        cls = Clazz.objects.get(cname=cname)
    except Clazz.DoesNotExist:
        cls = Clazz.objects.create(cname=cname)
    return cls

#获取科目对象
def getcourselist(*cournames):
   getcourselist = []
   for cn in cournames:
       try:
           cou = Course.objects.get(course_name=cn)
       except Course.DoesNotExist:
           cou = Course.objects.create(course_name=cn)
       getcourselist.append(cou)
       print(getcourselist)

   return getcourselist



def zhuceshuji(sname,cname,*cournames):
    #获取班级表数据
    cls = getCls(cname)
    # 获取课程对象列表
    courselist = getcourselist(*cournames)
    # 插入班级表数据
    try:
       stu= Student.objects.get(sname=sname)
    except Student.DoesNotExist:
       stu= Student.objects.create(sname=sname,cla=cls)

    #插入中间表数据
    stu.cour.add(*courselist)
    return True